/**
 * 
 */
package com.jsjvm.client.execution.objrepr.java;

import java.util.Arrays;

import com.jsjvm.client.classparser.JClass;
import com.jsjvm.client.classparser.JType;
import com.jsjvm.client.execution.JClassLoader;
import com.jsjvm.client.execution.JClassLoader.JClassNotLoadedException;
import com.jsjvm.client.execution.objrepr.ArrayRepr;

public class JavaArrayRepr extends JavaObjectRepr implements ArrayRepr {
	public Object[] array;

	public JavaArrayRepr(int size) {
		array = new Object[size];
	}

	@Override
	public Object get(int i) {
		return array[i];
	}

	@Override
	public void set(int i, Object val) {
		array[i] = val;
	}

	// Cache array object template
	public static ArrayRepr newJavaArrayRepr(String type, int size)
			throws JClassNotLoadedException {
		JClassLoader jcl = JClassLoader.getInstance();
		JClass superClass = jcl.getClassByName("java/lang/Object");

		JavaArrayRepr jo = new JavaArrayRepr(size);
		Arrays.fill(jo.array, JType.getDefaultElemValue(type));
		jo.putMembers(superClass);
		jo.jc = JClass.newArrayClass(type);

		return jo;
	}

	@Override
	public int length() {
		return array.length;
	}

	@Override
	public String toString() {
		String ret = "[";
		for (Object o : array) {
			ret += o.toString() + ",";
		}
		ret += "]";
		return ret;
	}
}